<template>
  <div>
    <van-nav-bar class="page-nav-bar" title="登录">
      <template #left>
        <van-icon name="cross" size="18"/>
      </template>
    </van-nav-bar>
    <van-form ref="loginForm" @submit="submitForm">
       <van-field
    v-model="mobile"
    name="mobile"
    placeholder="请输入手机号"
    :rules="[{ required: true, message: '请输入手机号' },{pattern:/^(?:(?:\+|00)86)?1\d{10}$/,message:'请输入正确的手机号'}]"
  >
  <template #label>
    <i class="iconfont icon-shouji"></i>
  </template>
  </van-field>
  <van-field
    v-model="code"
    type="number"
    name="code"
    placeholder="验证码"
    :rules="[{ required: true, message: '请填写验证码' },{pattern: /^\d{6}$/,message: '验证码格式错误'}]"
  >
  <template #label>
    <i class="iconfont icon-yanzhengma"></i>
  </template>
  <van-count-down
    v-if="isCountDownShow"
    slot="button"
    :time="1000 * 5"
    format="ss s"
    @finish="isCountDownShow = false"
  />
  <van-button
    v-else
    class="smsbtn"
    slot="button"
    size="small"
    type="primary"
    round
    @click="onSendSmsCode"
  >发送验证码</van-button>
  </van-field>
  <div style="margin: 16px;">
    <van-button  block type="info" native-type="submit">提交</van-button>
  </div>
    </van-form>
  </div>
</template>

<script>
import { getSmsCode } from '@/api/user'
export default {
  data () {
    return {
      mobile: '13333333333',
      code: '246810',
      isCountDownShow: false
    }
  },
  methods: {
    async submitForm (value) {
      // console.log(this.formData)
      await this.$store.dispatch('user/login', value)
      await this.$router.push('/my')
      this.$toast.success('登陆成功')
    },
    async onSendSmsCode () {
      console.log(1)
      // 先验证手机号
      try {
        await this.$refs.loginForm.validate('mobile')
      } catch (err) {
        return console.log('验证失败', err)
      }
      // 2. 验证通过，显示倒计时
      this.isCountDownShow = true
      // 3. 请求发送验证码
      try {
        await getSmsCode(this.mobile)
        this.$toast('发送成功')
      } catch (error) {
        this.isCountDownShow = false
        if (error.response.status === 429) {
          this.$toast('发送太频繁了，请稍后重试')
        } else {
          this.$toast('发送失败，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep .van-field__label{
  width: 18.5px;
  height: 26px;
  padding-right: 15px;
  .iconfont{
    font-size: 36px;
  }
}
::v-deep .smsbtn{
    background-color: #ccc;
    border: #ccc;
    color: #666;
  }

</style>
